/**
 * Created by chenxq on 2018/1/5.
 */
import React,{Component} from 'react';
import {Modal,message,Card,Button,Row,Col,Divider,Input,Popconfirm} from 'antd';
import {connect} from 'dva';
import request from '../../utils/request';
import styles from './index.less';


@connect(state=>({
  call:state.call
}))
export default class extends Component{
  static defaultProps={
    customerInfo:{}
  }
  constructor(props){
    super(props);
    this.state={
      visible:false,
      times:0 ,  // 通话时长
      callState:1 ,  // 1 拨电话 2 电话中 3 电话后
      remark:'',
      callId:0
    }
  }
  show=()=>{
    this.setState({
      visible:true,
      callId:0,
      times:0
    })
  }
  getExtra=()=>{
    return (<div>
      <Button type="danger">挂断</Button>
    </div>)
  }
  call=()=>{
    let {customerInfo={}} = this.props;
    let _this=this;
    this.props.dispatch({
      type:'call/fetchMakeCall',
      payload:customerInfo.id
    }).then(jsonData=>{
      if(!jsonData.result){
        message.error(jsonData.msg || '拨号失败');
      }else{
        _this.setState({
          callId:jsonData.data
        },()=>{
          _this.getStartTime(); // 开始查询
        });
      }
    })
  }

  componentWillReceiveProps(nextProps){
    let nextStatus=nextProps.call.status;
    let status=this.props.call.status;
    if(nextStatus != status){ // 表示状态变化
      if(nextStatus==2){ // 接通了
        this.startTime(); //开始计时
      }
      if(nextStatus==3){ //主动挂断或者被挂断了  两种
        this.timer && clearInterval(this.timer);
        this.getTimer && clearInterval(this.getTimer);
      }
    }
  }

  //查询 通话状态
  getCallStatus=()=>{
      if(!this.state.callId){
        return ;
      }
      let {customerInfo={}} = this.props;
      this.props.dispatch({
        type:'call/queryCallStatus',
        payload:{
          customerId:customerInfo.id,
          callId:this.state.callId
        }
      })
  }

  getStartTime=()=>{
    this.getTimer && clearInterval(this.getTimer);
    this.getTimer=window.setInterval(()=>{
        this.getCallStatus();
      },1*1000);

  }


  hangup=()=>{
    if(!this.state.callId){
      message.error('正在连接中，请稍等...');
      return ;
    }
    this.timer && clearInterval(this.timer);
    let {customerInfo={}} = this.props;
    this.props.dispatch({
      type:'call/hangUpCall',
      payload:{
        customerId:customerInfo.id,
        callId:this.state.callId
      }
    }).then(jsonData=>{
      if(jsonData.result){
        this.timer && clearInterval(this.timer);
      }
    })
  }

  startTime=()=>{
    let time=0;
    this.timer && clearInterval(this.timer);
    this.timer= window.setInterval(()=>{
      this.setState({
        times: time++
      })
    },1000)
  }
  cancel=()=>{
    let {customerInfo,call} = this.props;
    let status=call.status;
    let {info} = customerInfo;
    let _this=this;
    if(this.state.callId){
      if(status==1 || status==2){
        Modal.confirm({
          title: '提示',
          content: `您确定要取消与${info.name}的通话`,
          onOk(){
            _this.hangup();// 挂断电话
            _this.props.onChangeVisible && _this.props.onChangeVisible(false);
          }
        });
      }else{
        Modal.confirm({
          title:'提示',
          content:`确定不对本次通话做任何记录`,
          onCancel(){
          },
          onOk(){
            _this.props.onChangeVisible && _this.props.onChangeVisible(false);
          }
        })
      }
    }else{
      if(status==3){
        _this.props.onChangeVisible && _this.props.onChangeVisible(false);
      }else{
        message.error('正在连接中，请稍等...');
      }

    }
  }
  submit=()=>{
    let remark= this.state.remark;
    if(remark==''){
      message.error('备注不能为空');
      return;
    }
    let params={
      followContent:remark
    }
    this.followAdd(params);
  }
  componentDidMount(){
    this.call();
  }
  componentWillUnmount(){
    this.timer && clearInterval(this.timer);
    this.getTimer && clearInterval(this.getTimer);
  }
  addOneRecord=(shortcut)=>{
    this.followAdd({shortcut});
  }

  followAdd=(params)=>{
    let {customerInfo={}} = this.props;
    let customerId = customerInfo.id;
    let _this=this;
    this.props.dispatch({
      type:'follow/fetchAdd',
      payload:{
        customerId,
        params:{
          ...params,
          customerId
        }
      }
    }).then(jsonData=>{
      if (jsonData.result) {
        message.success('保存成功',0.8,()=>{
          _this.props.onChangeVisible && _this.props.onChangeVisible(false);
        });
      } else {
        message.error(jsonData.msg || '操作失败')
      }
    })
  }
  getTimeStr=()=>{
    let times=this.state.times;
    let hour=Math.floor(times/(60*60));
    let min=Math.floor((times-hour*60*60)/60);
    let sec=times-hour*60*60 - min*60;
    if(hour>0){
      return `${hour}时${min}分${sec}秒`;
    }
    if(min>0){
      return `${min}分${sec}秒`;
    }
    return `${sec}秒`
  }
  handleDetail=(type)=>{
    let _this=this;
    let {customerInfo={},dispatch} = this.props;
    let customerId = customerInfo.id;
    let url='';
    if(type=='intend'){
      url=`/v1/customer/intend/${customerId}`;
    }
    if(type=='quit'){
      url=`/v1/customer/quit`;
    }

    if(type=='invalid'){
      url=`/v1/customer/invalid`;
    }
    request(url,{
      method:'POST',
      body:[customerId]
    }).then(jsonData=>{
      if(jsonData.result){
        message.success('成功',0.8,()=>{
          dispatch({
            type:'customer/fetchCustomerDetail',
            payload:customerId
          });
          _this.props.onChangeVisible && _this.props.onChangeVisible(false);
        })
      }else{
        message.error(jsonData.msg || '操作失败');
      }
    })
  }
  render(){
    let {customerInfo={}} = this.props;
    let {status,type} = this.props.call;
    let info= customerInfo.info || {};
    let str=this.getTimeStr();
    return (<Modal style={{width:800}}
                   title={`与${info.name}通话`}
                   visible={true}
                   footer={null}
                   onCancel={this.cancel}

    >
      {status!=3 && <div className="flex-col flex-center">
        {
          status==2 ? <p>
            {type=='ANSWERED'?'分机应答':'被叫应答'}，通话时长：{str}
          </p>: <p>
            {this.state.callId?'拨号中...':'连接中...'}
          </p>
        }
        <Button size={'large'} className="hang-up" style={{backgroundColor:"#ff0000",borderColor: "#ff0000"}}  onClick={this.hangup}>{this.state.callId ?'挂断':'取消'}</Button>
      </div>}

      {status==3 && <Card title="通话反馈" style={{marginTop:20}} className="call-content">
        <div className="flex-row flex-center">
          <Button onClick={this.handleDetail.bind(this,'intend')}>意向</Button>
          <Popconfirm title="确定要将放弃该客户" onConfirm={this.handleDetail.bind(this,'quit')}>
            <Button title="确定要将该客户标记为无效">放弃</Button>
          </Popconfirm>

          <Popconfirm onConfirm={this.handleDetail.bind(this,'invalid')}>
            <Button>无效</Button>
          </Popconfirm>

        </div>
        <Divider/>
        <div>
          <h4>跟进记录-快捷操作</h4>
          <div >
            <div className="flex-row flex-center">
              <Popconfirm onConfirm={this.addOneRecord.bind(this, "halt")}
                          title={"标记为\"停机\"的用户将被加入到无效列表中，是否还需要继续将其标记为\"停机\"?"}><Button
                type="danger">停机</Button></Popconfirm>
              <Popconfirm onConfirm={this.addOneRecord.bind(this, "empty")}
                          title={"标记为\"空号\"的用户将被加入到无效列表中，是否还需要继续将其标记为\"空号\"?"}><Button
                type="danger">空号</Button></Popconfirm>
              <Popconfirm onConfirm={this.addOneRecord.bind(this, "shutdown")}
                          title={"标记为\"关机\"的用户将被加入到无效列表中，是否还需要继续将其标记为\"空号\"?"}><Button
                type="danger">关机</Button></Popconfirm>
            </div>
            <div className="flex-row flex-center" style={{marginTop:15}}>
              <Button onClick={this.addOneRecord.bind(this, "online")}>通话中</Button>
              <Button onClick={this.addOneRecord.bind(this, "miss")}>无人接听</Button>
              <Button onClick={this.addOneRecord.bind(this, "reject")}>无需求</Button>
            </div>
          </div>
          <Divider/>
          <div>
            <h4>备注</h4>
            <Input.TextArea onChange={(e)=>{
              this.setState({
                remark:e.target.value
              })
            }
            } placeholder="请输入备注" maxLength="200"

                            onPressEnter={this.submit}
            />
            <Button onClick={this.submit} type='primary' style={{marginTop:15,float:'right'}}>保存</Button>

          </div>

        </div>
      </Card>}

    </Modal>)
  }
}
